<template>
  <view class="product-detail-page">
    <view v-if="detail && detail.id">
      <!-- 轮播图全宽无白边 -->
      <swiper
        class="carousel"
        :indicator-dots="true"
        :autoplay="true"
        :interval="3000"
        :duration="500"
        v-if="detail.carouselImages && detail.carouselImages.length"
      >
        <swiper-item v-for="(img, idx) in detail.carouselImages" :key="idx">
          <image :src="img" mode="aspectFill" class="carousel-img" @error="onImgError(idx)" />
        </swiper-item>
      </swiper>

      <!-- 价格区块 -->
      <view class="price-block">
        <text class="goods-price">￥{{ detail.price }}</text>
        <text v-if="detail.originPrice" class="goods-origin-price">￥{{ detail.originPrice }}</text>
        <text class="promo-tag">限时秒杀</text>
        <text class="countdown">还剩 14:36:01</text>
      </view>

      <!-- 商品名称和副标题 -->
      <view class="goods-main">
        <view class="goods-title">{{ detail.goodsName }}</view>
        <view class="goods-intro">{{ detail.introduce }}</view>
      </view>

      <!-- 价格、销量、库存 -->
      <view class="goods-price-row">
        <text class="goods-sales">销量：{{ detail.sales }}</text>
        <text class="goods-inventory">库存：{{ detail.inventory }}</text>
      </view>

      <!-- 服务标签 -->
      <view class="service-tags" v-if="detail.services && detail.services.length">
        <text class="service-tag" v-for="item in detail.services" :key="item.title">{{ item.title }}</text>
      </view>

      <!-- 规格 -->
      <view class="spec-list" v-if="detail.specifications && detail.specifications.length">
        <view v-for="item in detail.specifications" :key="item.label" class="spec-item">
          <text class="spec-label">{{ item.label }}：</text>
          <text class="spec-value">{{ item.value }}</text>
        </view>
      </view>

      <!-- 分割线 -->
      <view class="section-divider"></view>

      <!-- 审批评论区域 -->
      <view class="review-section" @click="viewMoreReviews">
        <view class="review-header">
          <view class="review-title-wrapper">
            <text class="review-title">商品评价</text>
            <text class="review-count">({{ reviewList.length }})</text>
          </view>
          <text class="view-more-btn">查看更多 ></text>
        </view>

        <!-- 评价列表 -->
        <view class="review-list" v-if="reviewList.length > 0">
          <view
            v-for="review in reviewList.slice(0, 2)"
            :key="review.id"
            class="review-item"
          >
            <view class="review-user">
              <image :src="review.avatar || '/static/images/default-avatar.png'" class="user-avatar" mode="aspectFill" />
              <view class="user-info">
                <text class="user-name">{{ review.nickname }}</text>
                <view class="review-rating">
                  <text
                    v-for="i in 5"
                    :key="i"
                    :class="['star', { active: i <= review.evaluation }]"
                  >★</text>
                </view>
              </view>
              <text class="review-time">{{ formatTime(review.createTime) }}</text>
            </view>

            <view class="review-content">{{ review.content }}</view>

            <!-- 评价图片 -->
            <view class="review-images" v-if="review.imgUrl && review.imgUrl.length > 0">
              <image
                v-for="(img, index) in review.imgUrl.split(',')"
                :key="index"
                :src="img"
                class="review-img"
                mode="aspectFill"
                @click.stop="previewImage(review.imgUrl.split(','), index)"
              />
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view v-else class="review-empty">
          <text class="empty-text">暂无评价</text>
        </view>
      </view>

      <!-- 分割线 -->
      <view class="section-divider"></view>

      <!-- 图文详情 -->
      <view class="section-title">图文详情</view>
      <view class="detail-html" v-if="detail.detailContent">
        <image
          v-if="isImageUrl(detail.detailContent)"
          :src="detail.detailContent"
          mode="widthFix"
          style="max-width:100%;"
        />
        <rich-text
          v-else
          :nodes="detail.detailContent"
        ></rich-text>
      </view>
    </view>
    <view v-else style="margin: 100rpx auto; text-align: center; color: #888;">
      商品不存在
    </view>
    <!-- 固定底部购买操作区 -->
    <view class="buy-bar-fixed">
      <button class="btn-cart" @click="addToCart">加入购物车</button>
      <button class="btn-buy" @click="buyNow">立即购买</button>
    </view>
  </view>
</template>

<script>
import { getDetail } from '@/api/prodcut'
import { getReviewList } from '@/api/review/review'
import { addCart } from '@/api/cart'

export default {
  data() {
    return {
      productId: null,
      detail: null, // 初始为null，便于判断
      reviewList: [] // 评价列表
    }
  },
  onLoad(options) {
    this.productId = options.id;
    this.getProductDetail();
    this.getReviewList();
  },
  methods: {
    async getProductDetail() {
      uni.showLoading({ title: '加载中...' });
      try {
        const res = await getDetail(this.productId);
        // 适配接口直接返回商品对象
        const data = res.data ? res.data : res;
        if (data && data.id) {
          this.detail = data;
        } else {
          this.detail = null;
          uni.showToast({ title: '商品不存在', icon: 'none' });
        }
      } catch (e) {
        this.detail = null;
        uni.showToast({ title: '加载失败', icon: 'none' });
      } finally {
        uni.hideLoading();
      }
    },
    addToCart() {
      if (!this.$store.state.user.token) {
        uni.showToast({ title: '请先登录', icon: 'none' });
        setTimeout(() => {
          uni.navigateTo({ url: '/pages/login' });
        }, 800);
        return;
      }
      const userId = this.$store.state.user.id || uni.getStorageSync('userId');
      const productId = this.detail.id;
      addCart({ userId, productId, quantity: 1, checked: 1 }).then(res => {
        if (res.code === 200) {
          uni.showToast({ title: '加入购物车', icon: 'success' });
          // 可选：刷新购物车数量
        } else {
          uni.showToast({ title: res.msg || '加入失败', icon: 'none' });
        }
      }).catch(() => {
        uni.showToast({ title: '加入失败', icon: 'none' });
      });
    },
    buyNow() {
      uni.showToast({ title: '立即购买', icon: 'success' });
    },
    // 图片加载失败处理
    onImgError(idx) {
      if (this.detail && this.detail.carouselImages && this.detail.carouselImages.length > idx) {
        this.$set(this.detail.carouselImages, idx, '/static/logo.png');
      }
    },
    // 判断是否为图片链接
    isImageUrl(str) {
      return typeof str === 'string' &&
        (str.endsWith('.png') || str.endsWith('.jpg') || str.endsWith('.jpeg') || str.endsWith('.gif') || str.endsWith('.webp'));
    },

    // 获取评价列表
    async getReviewList() {
      try {
        const res = await getReviewList({
          productId: this.productId,
          page: 1,
          size: 10
        })
        if (res.code === 200 && res.data) {
          this.reviewList = Array.isArray(res.data) ? res.data : res.data.rows || []
        }
      } catch (error) {
        console.error('获取评价列表失败:', error)
      }
    },

    // 格式化时间
    formatTime(timeStr) {
      if (!timeStr) return ''
      const date = new Date(timeStr)
      const now = new Date()
      const diff = now - date

      // 小于1分钟
      if (diff < 60000) {
        return '刚刚'
      }
      // 小于1小时
      if (diff < 3600000) {
        return Math.floor(diff / 60000) + '分钟前'
      }
      // 小于24小时
      if (diff < 86400000) {
        return Math.floor(diff / 3600000) + '小时前'
      }
      // 小于30天
      if (diff < 2592000000) {
        return Math.floor(diff / 86400000) + '天前'
      }
      // 超过30天显示具体日期
      return date.toLocaleDateString()
    },

    // 预览图片
    previewImage(images, current) {
      uni.previewImage({
        urls: images,
        current: images[current]
      })
    },

    // 查看更多评价
    viewMoreReviews() {
      if (this.reviewList.length > 0) {
        uni.navigateTo({
          url: `/pages/product/reviews?productId=${this.productId}`
        })
      } else {
        uni.showToast({
          title: '暂无评价',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style scoped>
.product-detail-page { background: #fff; min-height: 100vh; padding-bottom: 120rpx; }
.carousel, .carousel-img {
  width: 100vw;
  height: 500rpx;
  border-radius: 0;
  margin: 0;
  display: block;
}
.price-block {
  background: linear-gradient(90deg, #ffefef, #fff);
  border-radius: 20rpx;
  padding: 18rpx 24rpx;
  margin: 0 24rpx 18rpx 24rpx;
  display: flex; align-items: center; flex-wrap: wrap;
}
.goods-price { color: #e64340; font-size: 44rpx; font-weight: bold; margin-right: 18rpx; }
.goods-origin-price { color: #999; font-size: 26rpx; text-decoration: line-through; margin-right: 18rpx; }
.promo-tag { background: #ff4d4f; color: #fff; border-radius: 8rpx; font-size: 22rpx; padding: 4rpx 12rpx; margin-right: 18rpx; }
.countdown { color: #ff4d4f; font-size: 24rpx; }
.goods-main { padding: 0 24rpx 0 24rpx; }
.goods-title { font-size: 40rpx; font-weight: bold; margin-bottom: 8rpx; color: #222; }
.goods-intro { color: #888; font-size: 26rpx; margin-bottom: 18rpx; }
.goods-price-row {
  display: flex; align-items: baseline; padding: 0 24rpx 0 24rpx; margin-bottom: 10rpx;
}
.goods-sales, .goods-inventory { color: #999; font-size: 24rpx; margin-right: 20rpx; }
.service-tags {
  display: flex; flex-wrap: wrap; margin: 0 24rpx 10rpx 24rpx;
}
.service-tag {
  background: #4caf50; color: #fff; border-radius: 8rpx; font-size: 22rpx; padding: 4rpx 12rpx; margin-right: 12rpx; margin-bottom: 8rpx;
}
.spec-list { padding: 0 24rpx 0 24rpx; margin-bottom: 10rpx; }
.spec-item { margin-bottom: 8rpx; font-size: 28rpx; }
.spec-label { color: #666; }
.spec-value { color: #333; }

/* 评价区域样式 */
.review-section {
  padding: 0 24rpx 20rpx 24rpx;
  margin-bottom: 20rpx;
  background: #fff;
  border-radius: 12rpx;
  cursor: pointer;
  transition: background-color 0.2s;
}

.review-section:active {
  background-color: #f8f8f8;
}

.review-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20rpx;
  padding: 20rpx 0 10rpx 0;
}

.review-title-wrapper {
  display: flex;
  align-items: center;
}

.review-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.review-count {
  font-size: 28rpx;
  color: #999;
  margin-left: 8rpx;
}

.view-more-btn {
  font-size: 28rpx;
  color: #666;
}

.review-list {
  margin-bottom: 20rpx;
}

.review-item {
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.review-item:last-child {
  border-bottom: none;
}

.review-user {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
}

.user-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  margin-right: 16rpx;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 4rpx;
  display: block;
}

.review-rating {
  display: flex;
  align-items: center;
}

.star {
  font-size: 24rpx;
  color: #ddd;
  margin-right: 2rpx;
}

.star.active {
  color: #ff6b35;
}

.review-time {
  font-size: 24rpx;
  color: #999;
}

.review-content {
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
  margin-bottom: 12rpx;
}

.review-images {
  display: flex;
  flex-wrap: wrap;
  gap: 8rpx;
}

.review-img {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
  background: #f5f5f5;
}

.review-empty {
  text-align: center;
  padding: 40rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}


.section-divider {
  height: 16rpx; background: #f7f7f7; margin: 0 0 0 0;
}
.section-title {
  font-size: 32rpx; font-weight: bold; margin: 30rpx 0 10rpx 24rpx;
}
.detail-html { margin: 0 24rpx 20rpx 24rpx; color: #444; font-size: 28rpx; }
.buy-bar-fixed {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100vw;
  background: #fff;
  display: flex;
  justify-content: space-around;
  padding: 16rpx 0 24rpx 0;
  box-shadow: 0 -2rpx 12rpx rgba(0,0,0,0.06);
  z-index: 99;
}
.btn-cart, .btn-buy {
  flex: 1;
  margin: 0 16rpx;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 30rpx;
  border-radius: 40rpx;
}
.btn-cart { background: #198cff; color: #fff; border: none; }
.btn-buy { background: #ff4d4f; color: #fff; border: none; }
</style>